package com.example.shoppingmall.cotroller;

import com.example.shoppingmall.Utils.Page;
import com.example.shoppingmall.config.MyLog;
import com.example.shoppingmall.pojo.*;
import com.example.shoppingmall.service.NoteService;
import com.example.shoppingmall.service.OrderService;
import com.example.shoppingmall.service.sms.SMSCode_payment;
import com.example.shoppingmall.service.sms.SMSCode_shipments;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.security.Principal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/order")
public class ShopController {
    @Autowired
    OrderService orderService;
    @Autowired
    NoteService noteService;

    String ordernos=null;
    String dates=null;
    String usernames=null;
    String phones=null;

    //分页查询+条件查询+排序
    @RequestMapping("/orderlist")
    public String orderlist(@RequestParam(value = "orderId",required = false) String orderId,
                            @RequestParam(value = "orderno",required = false) String orderno,
                            @RequestParam(value = "date",required = false) String date,
                            @RequestParam(value = "username",required = false) String username,
                            @RequestParam(value = "phone",required = false) String phone,
                            @RequestParam(value = "pageno",defaultValue = "1") Integer pageno,
                            @RequestParam(value = "pageSize",defaultValue = "6") Integer pageSize, Model model){
        model.addAttribute("orderno",orderno);
        model.addAttribute("date",date);
        model.addAttribute("username",username);
        model.addAttribute("phone",phone);
        if(orderId==null){
            orderId="0";
        }
        if(orderno!=null){
            ordernos=orderno;
        }if(date!=null){
            dates=date;
        }if(username!=null){
            username=usernames;
        }if(phone!=null){
            phones=phone;
        }
        int count=orderService.Count(Integer.valueOf(orderId),ordernos, dates, usernames, phones);
        int num=(Integer.valueOf(pageno)-1)*(Integer.valueOf(pageSize));
        Page page=new Page();
        page.setPageno(pageno);
        page.setPageSize(pageSize);
        page.setPageCount(count);
        List<Order> orderList=orderService.getOrderList(Integer.valueOf(orderId),ordernos,dates,usernames,phones,num,pageSize);
        model.addAttribute("page",page);
        model.addAttribute("orderList",orderList);
        model.addAttribute("counts",count);
        return "order/OrderList";
    }

    @MyLog(value = "订单管理->订单列表->跳转详情页")
    //根据id遍历数据
    @RequestMapping("/selxq")
    public String selxq(Integer id,Model model){
        Order order=orderService.selxq(id);
        model.addAttribute("order",order);
        return "order/OrderSelected";
    }

    @MyLog(value = "订单管理->订单列表->跳转修改页")
    //根据id查询数据修改
    @RequestMapping("/seledit")
    public String seledit(Integer id,Model model){
        Order order=orderService.selxq(id);
        model.addAttribute("order",order);
        return "order/OrderEdit";
    }

    @MyLog(value = "订单管理->订单列表->异步显示")
    //异步显示
    @RequestMapping("/sel")
    @ResponseBody
    public Map<Object,Object> sel(Integer id, HttpSession session){
        Map<Object,Object> map=new HashMap<>();
        Order order=orderService.selxq(id);
        map.put("orders",order);
        session.setAttribute("orders",order);
        return map;
    }

    @MyLog(value = "订单管理->订单列表->支付操作")
    //修改支付状态
    @RequestMapping("/pay")
    public String pay(@RequestParam("pay") String pay,HttpSession session){
        Order order= (Order) session.getAttribute("orders");
        int id=order.getId();
        String orderno=order.getOrderno();
        String username=order.getUsername();
        String phone=order.getPhone();
        Double money=order.getOrdermoney();
        //产生随机第三方单号
        int third_id=(int)(Math.random()*1000000000);
        Bill_payment billPayment=new Bill_payment();
        billPayment.setBill_id(orderno);
        billPayment.setBill_methodId(Integer.valueOf(pay));
        billPayment.setUsername(username);
        billPayment.setUserPhone(phone);
        billPayment.setMoney(money);
        billPayment.setThird_id(String.valueOf(third_id));
        User users=(User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        User user1 = orderService.getusermoney(users.getUsername());
        double usermoney = user1.getMoney();
        double moneysum = usermoney - money;
        if (Integer.valueOf(pay) == 3) {
            if (moneysum > 0) {
                User user = new User();
                user.setUserBalance(moneysum);
                user.setUserAccount(users.getUsername());
                orderService.updusermoney(user);
                if (orderService.updorderpay(Integer.valueOf(pay), Integer.valueOf(id)) > 0) {
                    //添加支付流水列表
                    if (orderService.addbillpayment(billPayment) > 0) {
//                    SMSCode_payment pays = new SMSCode_payment();
//                    try {
//                        pays.sendCode(phone);
//                        Note note = new Note();
//                        note.setPhone(phone);
//                        note.setTypeId(3);
//                        note.setContentId(3);
//                        noteService.add(note);
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
                        return "redirect:/order/orderlist";
                    }
                }
            }else{
                return "pay";
            }
        } else {
            if (orderService.updorderpay(Integer.valueOf(pay), Integer.valueOf(id)) > 0) {
                //添加支付流水列表
                if (orderService.addbillpayment(billPayment) > 0) {
//                    SMSCode_payment pays = new SMSCode_payment();
//                    try {
//                        pays.sendCode(phone);
//                        Note note = new Note();
//                        note.setPhone(phone);
//                        note.setTypeId(3);
//                        note.setContentId(3);
//                        noteService.add(note);
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
                    return "redirect:/order/orderlist";
                }
            }
        }
        return "error";
    }

    //发货
    @MyLog(value = "订单管理->订单列表->发货")
    @RequestMapping("/Delivergoods")
    public String edit(@RequestParam("CourierServices") String CourierServices,@RequestParam("CourierNo") String CourierNo,
                       @RequestParam("remarks") String remarks,HttpSession session){
        Order order= (Order) session.getAttribute("orders");
        int id=order.getId();
        String orderno=order.getOrderno();
        String username=order.getUsername();
        String name=order.getName();
        String address=order.getAddress();
        String phone=order.getPhone();
        //产生随机发货单号
        String InvoiceNo="11567453"+(int)(Math.random()*1000000000);
        Invoice invoice=new Invoice();
        invoice.setInvoiceNo(InvoiceNo);
        invoice.setCourierNo(CourierNo);
        invoice.setCourierServices(CourierServices);
        invoice.setOrderno(orderno);
        invoice.setUsername(username);
        invoice.setName(name);
        invoice.setAddress(address);
        invoice.setPhone(phone);
        invoice.setRemarks(remarks);
            if (orderService.updorderstatus(id) > 0) {
                //添加发货单列表
                if (orderService.addinvoiceOrder(invoice) > 0) {
                    //查询发货数量
                    Order orderid = orderService.selordershopid(id);
                    int ordershopid = orderid.getOrdershopId();
                    OrderShop already = orderService.selalreadynum(ordershopid);
                    int deliverno = already.getDeliverno();
                    //修改商品订单已发货数量
                    if (orderService.updordershopnum(deliverno, ordershopid) > 0) {
//                    SMSCode_shipments pays=new SMSCode_shipments();
//                    try {
//                        pays.sendCode(phone);
//                        Note note=new Note();
//                        note.setPhone(phone);
//                        note.setTypeId(4);
//                        note.setContentId(4);
//                        noteService.add(note);
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
                        return "redirect:/order/orderlist";
                    }

                }
            }
        return "error";
    }

    @MyLog(value = "订单管理->订单列表->完成")
    //订单完成修改
    @RequestMapping("/success")
    public String success(HttpSession session){
        Order order= (Order) session.getAttribute("orders");
        int id=order.getId();
        if(orderService.updordersuccess(id)>0){
            return "redirect:/order/orderlist";
        }
        return "error";
    }

    @MyLog(value = "订单管理->订单列表->编辑")
    //编辑
    @RequestMapping("/edit")
    public String edit(@RequestParam("id") String id,
                       @RequestParam("name") String name,
                       @RequestParam("phone") String phone,
                       @RequestParam("address") String address){
        Order order=new Order();
        order.setId(Integer.valueOf(id));
        order.setName(name);
        order.setAddress(address);
        order.setPhone(phone);
        if(orderService.updOrder(order)>0){
            return "redirect:/order/orderlist";
        }
        return "error";
    }
}
